<template>
	<view class="coin-page">
		<!-- Tabs -->
		<view class="tabs">
			<view :class="['tab-item', activeTab === 'market' ? 'active' : '']" @tap="switchTab('market')">市值</view>
			<view :class="['tab-item', activeTab === 'convert' ? 'active' : '']" @tap="switchTab('convert')">货币换算</view>
		</view>

		<view v-if="shownodata">
			，8干29日消息，据4E观察，目前美国市场上备案或申请的加密资产 ETP 产品已达 92 个，显示传统金融对加密市场工具的持续探索。
			与此同时，链上数据显示，比特币盈利钱包数量突破 5,500 万，创下历史新高，平均持币时长达 4.4 年。
		</view>
		<!-- 市值列表 -->
		<view v-if="activeTab === 'market' && showdata" class="market"  >
			<view class="market-header">
				<view class="col col-asset">币种 / 市值</view>
				<view class="col col-chart">走势图</view>
				<view class="col col-price">价格 / 涨跌幅</view>
			</view>
			<view class="divider" />
			
			<view class="market-list">
				<view v-for="(item, index) in marketList" :key="item.id" class="market-row" v-if="item">
				  <view class="col col-asset">
				    <view class="asset-line">
				      <image class="coin-logo" :src="item.logo || ''" mode="aspectFit" />
				      <view class="asset-texts">
				        <text class="coin-name">{{ item.fullname || item.name || '未知' }}</text>
				        <text class="coin-symbol">{{ item.name || item.code || '未知' }}</text>
				        <text class="market-cap">市值：{{ formatNumber(item.market_value || 0) }}</text>
				      </view>
				    </view>
				  </view>
				  
				  <view class="col col-chart">
				    <!-- CSS折线图走势图 -->
				    <view class="chart-container" v-if="item.klineDataArr && item.klineDataArr.length > 0">
				      <view class="css-line-chart">
				        <!-- 背景渐变填充 -->
				        <view 
				          class="chart-fill-bg"
				          :style="{
				            background: `linear-gradient(to bottom, ${getLineColor(item.klineDataArr)}15 0%, ${getLineColor(item.klineDataArr)}00 100%)`
				          }"
				        ></view>
				        
				        <!-- 连接线 -->
				        <view 
				          class="chart-line"
				          v-for="(line, lineIndex) in getChartLines(item.klineDataArr)"
				          :key="'line-' + lineIndex"
				          :style="{
				            left: line.x1 + '%',
				            bottom: line.y1 + '%',
				            width: line.length + 'px',
				            transform: `rotate(${line.angle}deg)`,
				            backgroundColor: getLineColor(item.klineDataArr)
				          }"
				        ></view>
				        
				        <!-- 数据点 -->
				        <view 
				          class="chart-point"
				          v-for="(point, pointIndex) in getChartPoints(item.klineDataArr)"
				          :key="pointIndex"
				          :style="{
				            left: point.x + '%',
				            bottom: point.y + '%',
				            backgroundColor: getLineColor(item.klineDataArr)
				          }"
				        ></view>
				      </view>
				    </view>
				    
				    <!-- 无数据时的占位图 -->
				    <view class="spark-placeholder" v-else>
				      <text class="placeholder-text">--</text>
				    </view>
				  </view>
				  
				  <view class="col col-price">
				    <view class="price-line">
				      <text class="price">¥ {{ formatPrice(item.current_price || 0) }}</text>
				      
				      <text :class="['change', (item.change_percent || 0) >= 0 ? 'up' : 'down']">
				        {{ (item.change_percent || 0) >= 0 ? '+' : '' }}{{ (item.change_percent || 0).toFixed(2) }}%
				      </text>
				    </view>
				  </view>
				</view>
				
				<!-- 空状态提示 -->
				<view v-if="!loading && marketList.length === 0" class="empty-state">
					<text>{{ loadError ? '加载失败' : '暂无数据' }}</text>
					<text class="empty-tip">{{ loadError ? '网络错误，请检查网络连接' : '下拉刷新或点击重试' }}</text>
					<view class="retry-btn" @tap="onRefresh">
						<text>{{ loadError ? '重新加载' : '点击重试' }}</text>
					</view>
				</view>
				
				<!-- 加载更多提示 -->
				<view v-if="loading" class="loading-more">
					<text>加载中...</text>
				</view>
				<view v-if="!hasMore && marketList.length > 0" class="no-more">
					<text>没有更多数据了</text>
				</view>
			</view>
		</view>

		<!-- 货币换算 -->
		<view v-if="activeTab === 'convert' && showdata" class="converter">
			<exchange 
				:key="activeTab"
				@currency-change="onExchangeCurrencyChange"
				@rate-update="onExchangeRateUpdate"
			></exchange>
		</view>
	</view>
</template>

<script>
	import exchange from '@/components/exchange.vue';
	import {gettickers,chek} from '@/api/user.js'
	export default {
		 components: {exchange},
		name: 'CoinPage',
		data() {
			return {
				shownodata:false,
				showdata:false,
				activeTab: 'market',
				tickersparam:{
					  param:{
					        "action":"coinrank",
					        "data[page]":1
					    },
					    c:"f",
					    m:"v2"
				},
				marketList: [],
				selectedCoinIndex: 0,
				amount: 1,
				currentPage: 1,
				hasMore: true,
				loading: false,
				refreshing: false,
				loadError: false,
				// exchange组件相关状态
				exchangeData: {
					lastRate: null,
					lastUpdate: null,
					currentPair: null
				}
			};
		},
		computed: {
			coinNames() {
				if (this.marketList.length === 0) return [];
				return this.marketList.map(c => `${c.nameZh || c.nameEn} (${c.abbreviation || c.nameEn})`);
			},
			selectedCoin() {
				if (this.marketList.length === 0) return null;
				return this.marketList[this.selectedCoinIndex] || this.marketList[0];
			},
			totalCny() {
				if (!this.selectedCoin) return 0;
				const price = Number(this.selectedCoin.priceUsd || 0) * 7.25;
				const amt = Number(this.amount) || 0;
				return price * amt;
			},
			// 检查是否有数据
			hasData() {
				return this.marketList && this.marketList.length > 0;
			}
		},
		onLoad() {
			// 页面加载时获取数据
			this.gettickersdata();
			chek().then(res=>{
			this.showdata = res.data;
			this.shownodata = !this.showdata;
		})
		},
		onShareAppMessage: function() {
						 return {
						 	title: this.miniHomeRemark,
						 	imageUrl: this.miniHomeImg,
						 	 path: '/pages/coin/coin'
						 };
						
					},
					onShareTimeline: function() {
						return {
							title: this.miniHomeRemark,
							imageUrl: this.miniHomeImg,
							path: '/pages/coin/coin'
						};
					},
		onPullDownRefresh() {
			// 小程序下拉刷新
			console.log('触发小程序下拉刷新');
			this.onRefresh();
		},
		
		onReachBottom() {
			// 小程序上拉触底
			console.log('触发小程序上拉触底');
			this.onLoadMore();
		},
		methods: {
			// 获取数据
			gettickersdata(isLoadMore = false) {

				
				if (this.loading) {
					console.log('正在加载中，跳过请求');
					return;
				}
				
				this.loading = true;
		

						
						const params = {
						 param:{
						       "action":"coinrank",
						       "data[page]": this.currentPage
						   },
						   c:"f",
						   m:"v2"
						};
						
				gettickers(params).then(res => {
					if (res.data ) {
						const newList = res.data;
						
						if (isLoadMore) {
							// 加载更多，追加数据
							this.marketList = [...this.marketList, ...newList];
						} else {
							// 首次加载或刷新，替换数据
							this.marketList = newList;
						}
						
						// 检查是否还有更多数据
						
				
						
						// 重置错误状态
						this.loadError = false;
						
						// 处理走势图数据
						this.$nextTick(() => {
							this.processSparklineData();
						});
					}
				}).catch(err => {
					console.error('获取数据失败:', err);
					this.loadError = true;
					uni.showToast({
						title: '网络错误，请检查网络连接',
						icon: 'none',
						duration: 2000
					});
					// 如果是首次加载失败，显示空状态
					if (!isLoadMore) {
						this.marketList = [];
						this.hasMore = false;
						this.selectedCoinIndex = 0;
					}
				}).finally(() => {
					this.loading = false;
					this.refreshing = false;
					
					// 停止小程序下拉刷新
					uni.stopPullDownRefresh();
				});
			},
			
			// 上拉加载更多
			onLoadMore() {

				if (!this.hasMore ) {
					console.log('阻止加载：', !this.hasMore ? '没有更多数据' : '正在加载中');
					return;
				}
				
				this.currentPage++;
				
				console.log('开始加载第', this.currentPage, '页');
				this.gettickersdata(true);
			},
			
			// 获取选中币种的显示文本
			getSelectedCoinDisplay() {
				if (this.marketList.length === 0) return '暂无数据';
				const coin = this.marketList[this.selectedCoinIndex];
				if (!coin) return '暂无数据';
				return `${coin.nameZh || coin.nameEn} (${coin.abbreviation || coin.nameEn})`;
			},
			
			// 下拉刷新
			onRefresh() {
				console.log('开始下拉刷新');
				this.refreshing = true;
				this.currentPage = 1;
				this.hasMore = true;
				this.gettickersdata(false);
			},
			
			switchTab(tab) {
				this.activeTab = tab;
				if (tab === 'market' && this.marketList.length > 0) {
					this.$nextTick(() => {
						this.processSparklineData();
					});
				} else if (tab === 'convert') {
					// 切换到货币换算tab时的处理
					console.log('切换到货币换算');
				}
			},
			onSelectCoin(e) {
				const newIndex = Number(e.detail.value);
				if (newIndex >= 0 && newIndex < this.marketList.length) {
					this.selectedCoinIndex = newIndex;
				}
			},
			formatPrice(n) {
				if (n === null || n === undefined || isNaN(n)) return '0.00';
				const num = Number(n);
				if (num >= 1000) return num.toLocaleString(undefined, { maximumFractionDigits: 2 });
				return num.toFixed(2);
			},
			formatNumber(n) {
				if (n === null || n === undefined || isNaN(n)) return '0';
				return Number(n).toLocaleString();
			},
			// 处理走势图数据
			processSparklineData() {
			  // 检查数据源是否存在
			  if (!this.marketList || this.marketList.length === 0) return;
			  
			  this.marketList.forEach((item, idx) => {
			    // 检查当前项和kline数据是否存在
			    if (item && item.kline_data) {
			      // 将逗号分隔的字符串转换为数值数组
			      const klineDataArr = item.kline_data.split(',').map(Number);
			      
			      // 检查转换后的数组是否有效
			      if (klineDataArr.length > 0 && !klineDataArr.some(isNaN)) {
			        // 缓存转换后的数据到item中
			        this.$set(item, 'klineDataArr', klineDataArr);
			      } else {
			        console.warn(`Invalid kline data for item ${item.id} at index ${idx}`);
			        this.$set(item, 'klineDataArr', []);
			      }
			    } else {
			      // 如果没有数据，创建一些模拟数据用于测试
			      const mockData = Array.from({length: 10}, () => 
			        Math.random() * 100 + 50
			      );
			      this.$set(item, 'klineDataArr', mockData);
			    }
			  });
			  
			  // CSS实现无需额外绘制操作
			},
			
			// 生成CSS折线图数据点
			getChartPoints(dataPoints) {
			  if (!dataPoints || dataPoints.length === 0) return [];
			  
			  const min = Math.min(...dataPoints);
			  const max = Math.max(...dataPoints);
			  const range = max - min || 1;
			  
			  // 限制点数量，最多显示20个点，确保性能和视觉效果
			  const maxPoints = 20;
			  const step = Math.max(1, Math.floor(dataPoints.length / maxPoints));
			  const filteredData = dataPoints.filter((_, i) => i % step === 0);
			  
			  // 生成CSS定位点
			  return filteredData.map((val, i, arr) => {
			    const x = arr.length === 1 ? 50 : (i / (arr.length - 1)) * 95 + 2.5; // x坐标：2.5-97.5%
			    const normalizedY = range === 0 ? 50 : ((val - min) / range) * 75 + 12.5; // y坐标：12.5-87.5%
			    return { 
			      x: x, 
			      y: normalizedY
			    };
			  });
			},
			
			// 生成平滑连接线数据
			getChartLines(dataPoints) {
			  const points = this.getChartPoints(dataPoints);
			  if (points.length < 2) return [];
			  
			  const lines = [];
			  const containerWidth = 120; // 预估容器宽度
			  const containerHeight = 32; // 预估容器高度
			  
			  // 为每两个点之间生成平滑曲线的小线段
			  for (let i = 0; i < points.length - 1; i++) {
			    const p1 = points[i];
			    const p2 = points[i + 1];
			    
			    // 计算控制点用于贝塞尔曲线
			    const prevPoint = i > 0 ? points[i - 1] : p1;
			    const nextPoint = i < points.length - 2 ? points[i + 2] : p2;
			    
			    // 生成平滑曲线的多个小线段
			    const segments = this.generateSmoothSegments(p1, p2, prevPoint, nextPoint, containerWidth, containerHeight);
			    lines.push(...segments);
			  }
			  
			  return lines;
			},
			
			// 生成平滑曲线线段
			generateSmoothSegments(p1, p2, prevPoint, nextPoint, containerWidth, containerHeight) {
			  const segments = [];
			  const segmentCount = 6; // 每两个点之间分成6段，平衡性能和平滑度
			  
			  // 计算控制点，使曲线更自然
			  const tension = 0.25; // 降低张力，让曲线更温和
			  
			  const cp1x = p1.x + (p2.x - prevPoint.x) * tension;
			  const cp1y = p1.y + (p2.y - prevPoint.y) * tension;
			  const cp2x = p2.x - (nextPoint.x - p1.x) * tension;
			  const cp2y = p2.y - (nextPoint.y - p1.y) * tension;
			  
			  // 生成贝塞尔曲线上的点
			  for (let j = 0; j < segmentCount; j++) {
			    const t = j / segmentCount;
			    const nextT = (j + 1) / segmentCount;
			    
			    // 三次贝塞尔曲线公式
			    const currentPoint = this.cubicBezier(t, p1, {x: cp1x, y: cp1y}, {x: cp2x, y: cp2y}, p2);
			    const nextPoint = this.cubicBezier(nextT, p1, {x: cp1x, y: cp1y}, {x: cp2x, y: cp2y}, p2);
			    
			    // 计算小线段
			    const deltaX = (nextPoint.x - currentPoint.x) * containerWidth / 100;
			    const deltaY = (nextPoint.y - currentPoint.y) * containerHeight / 100;
			    
			    const length = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
			    const angle = Math.atan2(deltaY, deltaX) * 180 / Math.PI;
			    
			    if (length > 0.3) { // 过滤掉太短的线段，减少DOM元素
			      segments.push({
			        x1: currentPoint.x,
			        y1: currentPoint.y,
			        length: length,
			        angle: angle
			      });
			    }
			  }
			  
			  return segments;
			},
			
			// 三次贝塞尔曲线计算
			cubicBezier(t, p0, p1, p2, p3) {
			  const u = 1 - t;
			  const tt = t * t;
			  const uu = u * u;
			  const uuu = uu * u;
			  const ttt = tt * t;
			  
			  return {
			    x: uuu * p0.x + 3 * uu * t * p1.x + 3 * u * tt * p2.x + ttt * p3.x,
			    y: uuu * p0.y + 3 * uu * t * p1.y + 3 * u * tt * p2.y + ttt * p3.y
			  };
			},
			
			// 获取线条颜色
			getLineColor(dataPoints) {
			  if (!dataPoints || dataPoints.length < 2) return '#999';
			  
			  const firstPrice = dataPoints[0];
			  const lastPrice = dataPoints[dataPoints.length - 1];
			  return lastPrice >= firstPrice ? '#16a34a' : '#ef4444';
			},
			
			// Exchange组件事件处理
			onExchangeCurrencyChange(data) {
				console.log('汇率组件货币变化:', data);
				// 更新当前货币对信息
				if (data.sourceCurrency && data.targetCurrency) {
					this.exchangeData.currentPair = `${data.sourceCurrency.code}_${data.targetCurrency.code}`;
				}
				
				// 可以在这里处理货币选择变化的逻辑
				// 例如：记录用户偏好、埋点统计等
				if (data.type === 'swap') {
					console.log('货币交换操作');
				} else {
					console.log(`${data.type}货币变更: ${data.oldCurrency?.code} -> ${data.newCurrency?.code}`);
				}
			},
			
			onExchangeRateUpdate(data) {
				console.log('汇率更新:', data);
				
				// 更新汇率状态
				if (data && data.rate) {
					this.exchangeData.lastRate = data.rate;
					this.exchangeData.lastUpdate = new Date(data.timestamp);
					
					// 如果汇率有显著变化，可以显示提示
					if (data.oldRate && Math.abs(data.rate - data.oldRate) / data.oldRate > 0.01) {
						const changePercent = ((data.rate - data.oldRate) / data.oldRate * 100).toFixed(2);
						console.log(`汇率变化: ${changePercent}%`);
						// 可以选择显示汇率变化提示
						// uni.showToast({
						//   title: `汇率变化${changePercent}%`,
						//   icon: 'none',
						//   duration: 1000
						// });
					}
				}
			}
		}
	};
</script>

<style scoped lang="less">
	.coin-page { 
		display: flex; 
		flex-direction: column; 
		height: 100vh; 
		background: #ffffff; 
		position: relative;
	}
	.tabs { 
		display: flex; 
		position: sticky; 
		top: 0; 
		z-index: 100; 
		background: #fff; 
		border-bottom: 1px solid #f0f0f0;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	}
	.tab-item { flex: 1; text-align: center; padding: 12px 0; font-size: 15px; color: #666; border-bottom: 2px solid transparent; }
	.tab-item.active { color: #111; font-weight: 600; border-bottom-color: #1677ff; }

	.market { 
		display: flex; 
		flex-direction: column; 
		flex: 1;
		position: relative;
		z-index: 1;
	}
	.market-header { display: flex; padding: 10px 12px; color: #888; font-size: 12px; }
	.col { display: flex; align-items: center; }
	.col-asset { flex: 1.2; gap: 8px; }
	.col-chart { 
		flex: 1; 
		justify-content: center; 
		position: relative;
		overflow: hidden;
	}
	.col-price { flex: 1; flex-direction: column; align-items: flex-end; gap: 4px; }
	.divider { height: 1px; background: #f0f0f0; margin: 0 12px; }
	.market-list { 
		flex: 1; 
		position: relative;
		z-index: 1;
		overflow-y: auto;
	}
	.market-row { display: flex; align-items: center; padding: 10px 12px; }
	.market-row + .market-row { border-top: 1px solid #f5f5f5; }

	.asset-line { display: flex; align-items: center; gap: 10px; }
	.coin-logo { width: 28px; height: 28px; border-radius: 50%; background: #f5f5f5; }
	.asset-texts { display: flex; flex-direction: column; }
	.coin-name { font-size: 14px; color: #111; }
	.coin-symbol { font-size: 12px; color: #888; }
	.market-cap { font-size: 12px; color: #666; }

	/* CSS折线图走势图样式 */
	.chart-container {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 36px;
		width: 100%;
		padding: 2px;
		position: relative;
		z-index: 1;
		border-radius: 4px;
		overflow: hidden;
	}
	
	.css-line-chart {
		width: 100%;
		height: 100%;
		position: relative;
		background: transparent;
	}
	
	/* 背景渐变填充 */
	.chart-fill-bg {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 1;
		border-radius: 2px;
	}
	
	/* 平滑连接线样式 */
	.chart-line {
		position: absolute;
		height: 1.2px;
		z-index: 2;
		transform-origin: left center;
		border-radius: 0.6px;
		opacity: 0.9;
		transition: all 0.3s ease;
	}
	
	/* 数据点样式 - 调整为更小更精致 */
	.chart-point {
		position: absolute;
		width: 2px;
		height: 2px;
		border-radius: 50%;
		z-index: 3;
		transition: all 0.3s ease;
		transform: translate(-50%, 50%);
		opacity: 0.7;
		box-shadow: 0 0 1px rgba(0, 0, 0, 0.3);
	}
	
	/* 为了更平滑的视觉效果，添加渐变阴影 */
	.chart-line::after {
		content: '';
		position: absolute;
		top: -0.5px;
		left: 0;
		right: 0;
		bottom: -0.5px;
		background: inherit;
		opacity: 0.3;
		border-radius: inherit;
		filter: blur(0.5px);
		z-index: -1;
	}
	
	/* 悬浮效果 */
	.chart-container:hover .css-line-chart {
		transform: scale(1.02);
	}
	
	.chart-point:hover {
		width: 4px;
		height: 4px;
		opacity: 1;
		box-shadow: 0 0 6px currentColor;
		transform: translate(-50%, 50%) scale(1.2);
	}
	
	/* 增强悬浮时的线条效果 */
	.chart-container:hover .chart-line {
		opacity: 1;
		height: 1.5px;
	}
	
	.chart-container:hover .chart-point {
		opacity: 0.9;
	}
	
	/* 走势图占位符 */
	.spark-placeholder {
		width: 100%;
		height: 36px;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
		z-index: 1;
		background: #f9f9f9;
		border-radius: 4px;
	}
	
	.placeholder-text {
		font-size: 12px;
		color: #ccc;
		font-weight: 500;
	}

	.price-line { display: flex; flex-direction: column; align-items: flex-end; }
	.price { font-size: 14px; color: #111; }
	.change { font-size: 12px; padding: 2px 6px; border-radius: 10px; }
	.change.up { color: #16a34a; background: #e8f5ee; }
	.change.down { color: #ef4444; background: #fdecec; }

	.loading-more, .no-more, .empty-state { 
		text-align: center; 
		padding: 20px 0; 
		color: #999; 
		font-size: 14px; 
	}
	
	.empty-state {
		color: #ccc;
		font-size: 16px;
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 10px;
	}
	
	.empty-tip {
		font-size: 12px;
		color: #999;
	}
	
	.retry-btn {
		padding: 8px 16px;
		background: #1677ff;
		color: #fff;
		border-radius: 20px;
		font-size: 14px;
	}
	
	.empty-converter {
		text-align: center;
		padding: 40px 20px;
		color: #999;
		font-size: 14px;
	}

	.converter { 
		padding: 16px; 
		display: flex; 
		flex-direction: column; 
		gap: 14px; 
		flex: 1;
		background: #f8f9fa;
		min-height: 0; /* 确保flex子元素可以正确缩放 */
	}
	.form-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
	.label { font-size: 14px; color: #444; }
	.picker-value { font-size: 14px; color: #111; padding: 8px 10px; background: #f7f7f7; border-radius: 8px; }
	.input { flex: 1; background: #f7f7f7; border-radius: 8px; padding: 8px 10px; font-size: 14px; }
	.result { margin-top: 10px; display: flex; flex-direction: column; gap: 6px; }
	.result-line { font-size: 13px; color: #666; }
	.result-total { font-size: 16px; font-weight: 600; color: #111; }
</style>